package com.interesting.client.UI.video;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.interesting.R;
import com.interesting.base.core.BaseFragment;
import com.interesting.base.http.HttpUtil;
import com.interesting.client.adapter.MusicListAdapter;
import com.interesting.client.bean.Music;
import com.interesting.client.support.video.MusicPlayer;

public class MusicFragment extends BaseFragment implements OnClickListener, OnItemClickListener, OnCompletionListener,
		OnSeekBarChangeListener {
	private TextView music_name;// 歌曲名
	private TextView music_author; // 歌手
	private CheckBox music_start;
	private SeekBar skbProgress; // 音乐进度条
	private ListView musicList;
	// private MediaPlayer media;
	private MusicPlayer player;
	private Button refresh;
	private String uri;
	private int progress;
	private List<Music> musicArray;
	private MusicListAdapter musicAdapter;
	private int currentPage = 1, totalPage = 1;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.video_music_fragment, container, false);
		music_name = (TextView) v.findViewById(R.id.music_fragment_name);
		music_author = (TextView) v.findViewById(R.id.music_fragment_author);
		skbProgress = (SeekBar) v.findViewById(R.id.music_fragment_seekBar);
		music_start = (CheckBox) v.findViewById(R.id.music_fragment_start);
		musicList = (ListView) v.findViewById(R.id.music_fragment_list);
		refresh = (Button) v.findViewById(R.id.music_fragment_refresh);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		refresh.setOnClickListener(this);
		music_start.setOnClickListener(this);
		musicList.setOnItemClickListener(this);
		player = new MusicPlayer(skbProgress);

		musicArray = new ArrayList<Music>();
		musicAdapter = new MusicListAdapter(getSherlockActivity(), musicArray);
		musicList.setAdapter(musicAdapter);
		if (savedInstanceState == null) {
			new MusicAsync().execute("1");
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.music_fragment_start: // 没有音乐列表 则开始按钮无法使用
			if (musicArray != null && !musicArray.isEmpty()) {
				music_start.setEnabled(true);
				if (player.isPlaying()) {
					player.pause();
				} else if (player.isPaused()) {
					player.start();
				} else {
					if (uri != null)
						player.playUri(getSherlockActivity(), uri);
				}
			} else {
				music_start.setEnabled(false);
			}
			break;
		case R.id.music_fragment_refresh:
			musicArray.clear();
			currentPage = currentPage % totalPage + 1;
			new MusicAsync().execute(currentPage + "");
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
		Music music = musicArray.get(position);
		uri = music.getVpath();
		player.playUri(getSherlockActivity(), uri);
		music_name.setText(music.getVtitle());
		music_author.setText(music.getVperson());
		music_start.setChecked(true);
	}

	@Override
	public void onStop() {
		player.stop();
		super.onStop();
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		this.progress = progress * player.getDuration() / seekBar.getMax();
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		player.seekTo(progress);
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		mp.start();
	}

	/** 获取 音乐列表 */
	private class MusicAsync extends AsyncTask<String, Void, JSONObject> {

		@Override
		protected JSONObject doInBackground(String... params) {
			Map<String, String> request = new HashMap<String, String>();
			request.put("act", "videoList");
			request.put("type", "0");
			request.put("currentPage", params[0]);
			return HttpUtil.parseResult(HttpUtil.post(request));
		}

		@Override
		protected void onPostExecute(JSONObject result) {
			if (result != null) {
				try {
					Gson gson = new Gson();
					List<Music> dataList = gson.fromJson(result.getString("dataList"), new TypeToken<List<Music>>() {
					}.getType());
					for (int i = 0; i < dataList.size(); i++) {
						musicArray.add(dataList.get(i));
					}
					currentPage = result.getInt("currentPage");
					totalPage = result.getInt("totalPage");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				musicAdapter.notifyDataSetChanged();
			}

			super.onPostExecute(result);
		}

	}
}
